package cn.zzzyuan.controller;


import cn.zzzyuan.common.content.ResponseContent;
import cn.zzzyuan.common.entity.ResponseResult;
import cn.zzzyuan.entity.Content;
import cn.zzzyuan.entity.Doc;
import cn.zzzyuan.entity.Ebook;
import cn.zzzyuan.entity.User;
import cn.zzzyuan.entity.vo.DocVo;
import cn.zzzyuan.service.ContentService;
import cn.zzzyuan.service.DocService;
import cn.zzzyuan.service.EbookService;
import cn.zzzyuan.service.UserService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;

/**
 * <p>
 * 用户 前端控制器
 * </p>
 *
 * @author
 * @since 2022-04-13
 */
@RestController
@RequestMapping("/user")
public class UserController {

    private final UserService userService;
    public UserController(UserService userService) {
        this.userService = userService;
    }
    @PostMapping("/save")
    public ResponseResult addDoc(@RequestBody User user) {
        user.setPassword(new BCryptPasswordEncoder().encode(user.getPassword()));
        userService.save(user);
        return ResponseResult.success(ResponseContent.ERROR.msg(),ResponseContent.ERROR.code(),-1);
    }


    @GetMapping("/delete")
    public ResponseResult deleteDoc(@RequestParam("id")Long id) {

        boolean book=userService.removeById(id);
        if(book){
            return ResponseResult.success(ResponseContent.SUCCESS.msg(),ResponseContent.SUCCESS.code(),1);
        }
        return ResponseResult.success(ResponseContent.ERROR.msg(),ResponseContent.ERROR.code(),-1);

    }
    @GetMapping("/all")
    public ResponseResult getContent(){
        return ResponseResult.success(userService.list());
    }
    @GetMapping("/update")
    public ResponseResult getContent(@RequestBody User newUser){
        User oldUser= userService.getOne(new QueryWrapper<User>().eq("id",newUser.getId()));
        if(oldUser!=null){
            userService.updateById(oldUser);
            return ResponseResult.success(ResponseContent.SUCCESS.msg(),ResponseContent.SUCCESS.code(),1);
        }
        userService.save(newUser);
        return ResponseResult.success(ResponseContent.ERROR.msg(),ResponseContent.ERROR.code(),-1);
    }

    @PostMapping("/login")
    public ResponseResult login(@RequestBody User user){
        User loginName = userService.getOne(new QueryWrapper<User>().eq("login_name", user.getLoginName()));
        if(loginName != null){
            if(new BCryptPasswordEncoder().matches(loginName.getPassword(), user.getPassword())){
                return ResponseResult.success(loginName);
            }
            return ResponseResult.error("密码错误",401,null);
        }
        return ResponseResult.error("无此用户",401,null);
    }

}
